﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GGEditor.API.Commands;
using GGEditor.API.Editors;

namespace GGEditor.API.Samples.LandAndWater
{
	public class Controller : IEditorController
	{
		private ICommandManager<Model> commandManager;
		private ICommandOperation<Model> operation;

		public Controller(ICommandManager<Model> commandManager)
		{
			this.commandManager = commandManager;
		}

		#region Implementation of IEditorController

		public void SubscribeTo(IEditorView view)
		{
			IViewListener listener = view as IViewListener;
			if (listener == null)
				return;

			listener.GridSquareMouseDown += GridSquareMouseDown;
			listener.GridSquareMouseDrag += OnGridSquareMouseDrag;
			listener.GridSquareMouseUp += GridSquareMouseUp;
			listener.KeyUp += OnKeyUp;
		}

		void OnKeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Escape && operation != null)
			{
				operation.Cancel();
				operation = null;
			}
		}

		public void UnsubscribeFrom(IEditorView view)
		{
			IViewListener listener = view as IViewListener;
			if (listener == null)
				return;

			listener.GridSquareMouseDown -= GridSquareMouseDown;
			listener.GridSquareMouseDrag -= OnGridSquareMouseDrag;
			listener.GridSquareMouseUp -= GridSquareMouseUp;
		}

		void GridSquareMouseDown()
		{
			if (operation != null)
				GridSquareMouseUp();

			operation = commandManager.BeginOperation("edit tiles");
		}

		void GridSquareMouseUp()
		{
			if (operation == null)
				return;

			operation.End();
			operation = null;
		}

		void OnGridSquareMouseDrag(int x, int y, bool leftClick)
		{
			if (operation == null)
				return;

			operation.Do(new Command<Model>()
				{
					Do = delegate(Model model)
					{
						model[x, y] = leftClick;
					},
					Undo = delegate(Model model)
					{
						model[x, y] = !leftClick;
					}
				});
		}


		#endregion
	}
}
